package com.sinosoft.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;

import com.sinosoft.castor.CastorUtil;
import com.sinosoft.common.bean.SessionObj;
import com.sinosoft.common.db.DaoUtil;
import com.sinosoft.common.db.StaticDaoUtil;
import com.sinosoft.domain.base.BaseCompany;
import com.sinosoft.domain.base.BaseUser;
import com.sinosoft.domain.base.BaseUserCompany;

/**
 * 权限工具类
 * 
 * @author unhappydepig
 * @mail yqw8912@163.com
 * @time 2015-5-6 下午3:19:48
 */
public class PowerUtil {

	private static DaoUtil daoUtil = new DaoUtil(StaticDaoUtil.getDao());

	/**
	 * 根据用户SessionId获取默认权限
	 * 
	 * @param sessionId
	 * @return
	 */
	public static String[] getComArrayBySessionId(String sessionId) {
		return getComArrayBySessionId(sessionId, Constans.P_SELF_NEXY_SUB);
	}
	/**
	 * 根据SessionId获取
	 * 
	 * @param sessionId
	 * @return
	 */
	public static String[] getComArrayBySessionId(String sessionId,
			int powerLevel) {
		SessionObj sessionObj = CacheConstans.sessionMap.get(sessionId);
		if (null != sessionObj) {// 说明用户没用登录
			if (null != sessionObj.getComArrayMap()
					&& sessionObj.getComArrayMap().containsKey(powerLevel)) {
				return sessionObj.getComArrayMap().get(powerLevel);
			} else {
				String userId = sessionObj.getBaseUser().getUserId();
				String[] comArray = getComArrayByUserId(userId, powerLevel);
				sessionObj.getComArrayMap().put(powerLevel, comArray);
				return comArray;
			}
		}
		return null;
	}

	/**
	 * 根据用户Id获取
	 * 
	 * @param userId
	 * @return
	 */
	public static String[] getComArrayByUserId(String userId) {
		return getComArrayByUserId(userId, Constans.P_SELF_NEXY_SUB);
	}
	/**
	 * 根据用户ID
	 * @param userId
	 * @param powerLevel
	 * @return
	 */
	public static String[] getComArrayByUserId(String userId, int powerLevel) {
		String[] powerArray = new String[] {};
		BaseUser user = daoUtil.detailByPK(BaseUser.class, userId);
		if (null == user) {
			return null;
		}
		Map<String,String> userCom = getUserComList(userId);
		Map<String,String> powerCom = new HashMap<String,String>();
		String deptId = user.getDeptId();
		switch (powerLevel) {
		case Constans.P_USER://超级用户
			powerCom.put(userId, userId);			
			break;
		case Constans.P_SUPER://超级用户
			powerCom = getSuper(userId);			
			break;
		case Constans.P_SELF://本身
			powerCom = getSelf(userId,deptId);	
			powerCom.putAll(userCom);
			break;
		case Constans.P_SELF_SUB://本身及所有子集
			powerCom = getSub(userId, deptId);		
			powerCom.putAll(userCom);	
			powerCom.put(deptId,deptId);
			break;
		case Constans.P_SELF_NEXY_SUB://本身及下级子集
			powerCom = getSupComMap(deptId);
			powerCom.putAll(userCom);
			powerCom.put(deptId,deptId);
			break;
		case Constans.P_SUB://所有子集
			powerCom = getSub(userId, deptId);
			powerCom.putAll(userCom);
			powerCom.remove(deptId);
			break;
		case Constans.P_NEXY_SUB://下级子集
			powerCom = getSupComMap( deptId);
			powerCom.remove(deptId);
			powerCom.putAll(userCom);
			break;
		case Constans.P_SELF_UP://当前及所有上级
			powerCom = getUp(deptId);
			powerCom.put(deptId, deptId);
			break;
		}
		powerArray = CastorUtil.castTo(powerCom, String[].class);
		return powerArray;
	}
	/**
	 * 查询所有字迹
	 * @param userId
	 * @param deptId
	 * @return
	 */
	private static Map<String,String> getSub(String userId, String deptId) {
		Map<String,String> comMap = new HashMap<String,String>();
		getAllSupComList(comMap, deptId);
		return comMap;
	}
	/**
	 * 查询所有字迹
	 * @param userId
	 * @param deptId
	 * @return
	 */
	private static Map<String,String> getUp(String deptId) {
		Map<String,String> comMap = new HashMap<String,String>();
		getAllUpComList(comMap, deptId);
		return comMap;
	}	
	/**
	 * 超级用户
	 * @param userId
	 * @return
	 */
	private static Map<String,String> getSuper(String userId) {
		Map<String,String> comMap = new HashMap<String,String>();
		Sql sql = Sqls.create("SELECT COM_ID FROM T_BASE_COMPANY");
		sql.setCallback(Sqls.callback.entities());
		List<BaseCompany> list = daoUtil.list(BaseCompany.class, sql);
		for (int i = 0; i < list.size(); i++) {
			comMap.put(list.get(i).getComId(),list.get(i).getComId());				
		}
		return comMap;
	}

	/**
	 * 根据机构代码获取下级机构代码
	 * 
	 * @return
	 */
	private static void getAllSupComList(Map<String,String> comMap,String upComId) {
		Sql sql = Sqls.create("select com_id from T_BASE_COMPANY where up_com_id =@upComId");
		sql.params().set("upComId", upComId);
		sql.setCallback(Sqls.callback.entities());
		List<BaseCompany> list = daoUtil.list(BaseCompany.class, sql);
		List<String> powerList = new ArrayList<String>();
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				powerList.add(list.get(i).getComId());
			}
		}
		for (Iterator<String> iter = powerList.iterator(); iter.hasNext();) {
			String comId = iter.next();
			if(!comMap.containsKey(comId)){
				comMap.put(comId, comId);				
				getAllSupComList(comMap, comId);
			}
			
		}		
	}
	/**
	 * 根据机构代码获取上级机构代码
	 * @return
	 */
	private static void getAllUpComList(Map<String,String> comMap,String comId) {
		Sql sql = Sqls.create("select up_com_id from T_BASE_COMPANY where com_id =@comId");
		sql.params().set("comId", comId);
		sql.setCallback(Sqls.callback.entities());
		List<BaseCompany> list = daoUtil.list(BaseCompany.class, sql);
		List<String> powerList = new ArrayList<String>();
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				powerList.add(list.get(i).getUpComId());
			}
		}
		for (Iterator<String> iter = powerList.iterator(); iter.hasNext();) {
			String upComId = iter.next();
			if(!comMap.containsKey(upComId)){
				comMap.put(upComId, upComId);				
				getAllUpComList(comMap, upComId);
			}
			
		}		
	}	
	/**
	 * 根据机构代码获取下级机构代码
	 * 
	 * @return
	 */
	private static Map<String,String> getSupComMap(String upComId) {
		Map<String,String> comMap = new HashMap<String,String>();
		Sql sql = Sqls.create("select * from T_BASE_COMPANY where up_com_id =@upComId");
		sql.params().set("upComId", upComId);
		sql.setCallback(Sqls.callback.entities());
		List<BaseCompany> list = daoUtil.list(BaseCompany.class, sql);
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				comMap.put(list.get(i).getComId(),list.get(i).getComId());				
			}
		}
		return comMap;
	}
	/**
	 * 根据用户ID获取当前的机构
	 * 
	 * @return
	 */
	private static Map<String,String> getSelf(String userId, String deptId) {
		Map<String,String> comMap = new HashMap<String,String>();
		comMap.put(deptId,deptId);	
		return comMap;
	}
	/**
	 * 获取用户额外授权的机构
	 * @return
	 */
	private static Map<String,String> getUserComList(String userId) {
		Sql sql = Sqls.create("select * from T_BASE_USER_COMPANY where user_id =@userId");
		sql.params().set("userId", userId);
		sql.setCallback(Sqls.callback.entities());
		List<BaseUserCompany> list = daoUtil.list(BaseUserCompany.class, sql);
		Map<String,String> comMap = new HashMap<String,String>();
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				comMap.put(list.get(i).getComId(),list.get(i).getComId());				
			}
		}
		return comMap;
	}	
}
